package com.lening.collect.controller;

/**
 * @ToDo:
 * @Author：杨军
 * @date: 2024/05/27 07:34
 */

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.lening.collect.pojo.Alipay;
import com.lening.common.web.Request;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("pay")
@Slf4j
@CrossOrigin
public class PayController {
    @Autowired(required = false)
    private PledgeController pledgeController;
    private final String APP_ID = "9021000137636514";
    private final String APP_PRIVATE_KEY = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCLnc2mWhEtfn5RZrPcEhRp2HCz0HFKGEGeyPh2SXgK6jFHxq22dF8khCKsRuKI9M3dzZFQS0KEUxYSRQPeoZ/apGtPYnAQsaGSx6qZ/veRtK9yarosmNSw5uP3AlvQQiv0BRgHsa11Lpj8WS5WbBgysRCKO3sgSYQ/UyTjph3PL2H6icaqRhdkBgCLNEz7LWsPLvTDblHLezPUfbJFlcscWHIOGqwu4jCxXoFZCThsI7opsaDPFW3B000dfP99dIT7XLLAMDe/rcOEt9/xChsWo4FPkO7akbBIW4Cw2ipYLvvjD+WNc34XcowavGE45NMVXERLXvommywy327xZeXnAgMBAAECggEBAIB1KgEz/3gXWYv17ei/Lc8RWOjpEUN2O/InwQu8n1mTjtIWiEBGpD+J4AkYk1glvcClYl05UbNEaxtWKrBNjzHxc9avoKKLfTj6wwo7oHeMgpzIfBGKcK9vUTI1Flrwd1Zm1WxG22zk+de9Cjhz7n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UTF-8";
    private final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjf6yhWGFjPUQPFwyqTzGFfLRVt8e4HqErW01tDAFOgI7LIWJelq3NHhq9F5IGTW8PRTvKVixWVMTDmirnXsTmOiy00UtN7P6pV9ZsAt6vBjY5Tu79rbeer7LCGzsGOpbNszuAowcNk/1jW3kzE/7qc1HxOCwuNwtmgMu0BiPGBNJVYM2RDqpFPvN7DoG29O+zsaNe381P1z2T+f9ZfH/Ukf2/iC/OG6GviOZsdpKutS4D7NVqcifktqpXjnveUZ4Ohs4H6lg70wSEdkbMGXqYZ+1DsOkOzZLO+nDdKP5F2ZQJkDCkHwJMhk03Si/LxZo5LsDLM/Nm3AxjzAFC7Wl6QIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
    private final String NOTIFY_URL = "http://75fz3t.natappfree.cc/pay/returnUrl";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
    private final String RETURN_URL = "http://localhost:8099/collect/pledge";

    @RequestMapping("alipay")
    public void alipay(@RequestBody Alipay alipay, HttpServletResponse httpResponse) throws IOException {
        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl(RETURN_URL);
        request.setNotifyUrl(NOTIFY_URL);
        //根据订单编号,查询订单相关信息
//        Order order = IPayService.selectById(orderId);
        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = alipay.getId();
        //付款金额，必填
        String total_amount = alipay.getPledge().toString();
        //订单名称，必填
        String subject = alipay.getName();
        //商品描述，可空
        String body = "";
        request.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        Long id= Long.valueOf(out_trade_no);
        log.info(String.valueOf(id));
        pledgeController.updateStatusPayInt(id);
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }


    @PostMapping(value = "/returnUrl")
    public String returnUrl(HttpServletRequest request, HttpServletResponse response)
            throws IOException, AlipayApiException {
        System.out.println("=================================同步回调=====================================");
        // 获取支付宝GET过来反馈信息

        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("utf-8"), "utf-8");
            params.put(name, valueStr);
        }

        System.out.println(params);//查看参数都有哪些
        boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, SIGN_TYPE); // 调用SDK验证签名
//验证签名通过
        if(signVerified){
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

            System.out.println("商户订单号="+out_trade_no);
            System.out.println("支付宝交易号="+trade_no);
            System.out.println("付款金额="+total_amount);

            //支付成功，修复支付状态
            // payService.updateById(Integer.valueOf(out_trade_no));

            return "ok";//跳转付款成功页面
        }else{
            return "no";//跳转付款失败页面
        }
    }
    @RequestMapping("refund")
    public void toRefund(HttpServletResponse response, HttpSession session,@RequestBody Alipay alipay) throws IOException, AlipayApiException {
        // 设置编码格式
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        //设置请求参数
        AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();
        //商户订单号，必填
        String out_trade_no = alipay.getId();
        //需要退款的金额，该金额不能大于订单金额，必填
        String refund_amount = alipay.getPledge().toString();
        //标识一次退款请求，同一笔交易多次退款需要保证唯一。如需部分退款，则此参数必传；不传该参数则代表全额退款
        String out_request_no = new String(String.valueOf(UUID.randomUUID()));
        // 字符转义很重要
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"refund_amount\":\""+ refund_amount +"\","
                + "\"out_request_no\":\""+ out_request_no +"\"}");
        //请求
        String result = alipayClient.execute(alipayRequest).getBody();
        //输出
        out.println(result);//以下写自己的订单退款代码
        log.info("返回结果={}",result);
    }

}